<template>
  <div class="books-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="category-card">
          <template #header>
            <div class="category-header">
              <div class="title">
                <el-icon><Folder /></el-icon>
                <span>图书分类</span>
              </div>
              <div class="category-actions">
                <el-tooltip effect="dark" content="编辑分类" placement="top">
                  <el-button
                    type="primary"
                    :icon="Edit"
                    circle
                    :disabled="!selectedCategory"
                    @click="handleEditCategory"
                  />
                </el-tooltip>
                <el-tooltip effect="dark" content="添加新分类" placement="top">
                  <el-button
                    type="primary"
                    :icon="Plus"
                    circle
                    @click="handleAddCategory"
                  />
                </el-tooltip>
              </div>
            </div>
          </template>
          <div class="category-tree">
            <el-tree
              :data="categories"
              :props="defaultProps"
              @node-click="handleNodeClick"
              default-expand-all
            />
          </div>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card class="book-list">
          <div class="search-form">
            <el-form :inline="true" @submit.prevent="handleSearch">
              <el-form-item label="书名">
                <el-input
                  v-model="searchForm.bookName"
                  placeholder="请输入书名"
                  clearable
                />
              </el-form-item>
              <el-form-item label="作者">
                <el-input
                  v-model="searchForm.author"
                  placeholder="请输入作者"
                  clearable
                />
              </el-form-item>
              <el-form-item label="分类">
                <el-cascader
                  v-model="searchForm.category"
                  :options="categories"
                  :props="cascaderProps"
                  clearable
                  placeholder="请选择分类"
                />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="searchForm.status" clearable placeholder="请选择状态" style="width: 120px">
                  <el-option label="在库" :value="0" />
                  <el-option label="借出" :value="1" />
                  <el-option label="维护中" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
                <el-button type="success" @click="handleAddBook">新增图书</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table 
            v-loading="tableLoading" 
            :data="tableData" 
            style="width: 100%"
            @sort-change="handleSortChange"
          >
            <el-table-column prop="book_id" label="编号" width="100" sortable="custom"/>
            <el-table-column prop="title" label="书名" width="200" />
            <el-table-column prop="author" label="作者" width="150" />
            <el-table-column prop="isbn" label="ISBN" width="150" />
            <el-table-column prop="publisher" label="出版社" width="150" />
            <el-table-column prop="location" label="馆藏位置" width="120" />
            <el-table-column prop="total_copies" label="总数量" width="90" />
            <el-table-column prop="available_copies" label="可借数量" width="90" />
            <el-table-column prop="book_status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.book_status)">
                  {{ getStatusText(row.book_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditBook(row)">编辑</el-button>
                <el-button link type="success" @click="handleViewBook(row)">详情</el-button>
                <el-button 
                  link 
                  type="danger" 
                  @click="handleChangeStatus(row)"
                  :disabled="row.book_status === 1"
                >
                  {{ row.book_status === 0 ? '下架' : '上架' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑分类弹窗 -->
    <el-dialog
      v-model="categoryDialog.visible"
      :title="categoryDialog.type === 'add' ? '新增分类' : '编辑分类'"
      width="30%"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
        <el-form-item label="上级分类">
          <el-cascader
            v-model="categoryForm.parentId"
            :options="categories"
            :props="cascaderProps"
            clearable
            placeholder="请选择上级分类"
          />
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number v-model="categoryForm.sort" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveCategory">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑图书弹窗 -->
    <el-dialog
      v-model="bookDialog.visible"
      :title="bookDialog.type === 'add' ? '新增图书' : '编辑图书'"
      width="50%"
    >
      <el-form
        ref="bookFormRef"
        :model="bookForm"
        :rules="bookRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="cover-section">
              <div class="section-title">图书封面</div>
              <el-upload
                class="book-cover-uploader"
                :show-file-list="false"
                :before-upload="beforeCoverUpload"
                :http-request="handleCoverSuccess"
              >
                <div class="cover-preview">
                  <img
                    v-if="bookForm.cover"
                    :src="bookForm.cover"
                    class="book-cover"
                  />
                  <div v-else class="upload-placeholder">
                    <el-icon class="book-cover-uploader-icon"><Plus /></el-icon>
                    <span>上传封面</span>
                  </div>
                </div>
              </el-upload>
              <div class="upload-tip">
                建议尺寸: 350x500px<br/>
                支持 jpg、png 格式
              </div>
            </div>
          </el-col>
          <el-col :span="16">
            <el-form-item label="所属分类" prop="category_id">
              <el-cascader
                v-model="bookForm.category_id"
                :options="categories"
                :props="cascaderProps"
                clearable
                placeholder="请选择图书分类"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="书名" prop="title">
              <el-input v-model="bookForm.title" />
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input v-model="bookForm.author" />
            </el-form-item>
            <el-form-item label="ISBN" prop="isbn">
              <el-input v-model="bookForm.isbn">
                <template #append>
                  <el-button :icon="Camera" @click="openScanner" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="出版社" prop="publisher">
              <el-input v-model="bookForm.publisher" />
            </el-form-item>
            <el-form-item label="出版日期" prop="publish_date">
              <el-date-picker
                v-model="bookForm.publish_date"
                type="date"
                placeholder="选择出版日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="图书总数" prop="total_copies">
              <el-input-number
                v-model="bookForm.total_copies"
                :min="1"
                controls-position="right"
                style="width: 100%"
                @change="handleTotalCopiesChange"
              />
            </el-form-item>    
            <el-form-item label="已借阅数" prop="borrow_copies">
              <el-input-number
                v-model="bookForm.borrow_copies"
                :min="0"
                controls-position="right"
                style="width: 100%"
                @change="handleTotalCopiesChange"
              />
            </el-form-item>        
            <el-form-item label="馆藏位置" prop="location">
              <el-input v-model="bookForm.location" />
            </el-form-item>
            <el-form-item label="状态" prop="book_status">
              <el-select v-model="bookForm.book_status" placeholder="请选择图书状态">
                <el-option label="在库" :value="0" />
                <el-option label="借出" :value="1" />
                <el-option label="维护中" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="图书简介" prop="description">
              <el-input
                v-model="bookForm.description"
                type="textarea"
                :rows="4"
                :maxlength="500"
                show-word-limit
                placeholder="请输入图书简介（最多500字）"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bookDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveBook">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图书详情预览弹窗 -->
    <el-dialog
      v-model="previewDialog.visible"
      title="图书详情"
      width="50%"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="图书封面" :span="2">
          <el-image
            v-if="previewBook.book_cover"
            :src="previewBook.book_cover"
            fit="contain"
            style="width: 120px; height: 160px"
          />
          <span v-else>暂无封面</span>
        </el-descriptions-item>
        <el-descriptions-item label="书名">{{ previewBook.title }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ previewBook.author }}</el-descriptions-item>
        <el-descriptions-item label="ISBN">{{ previewBook.isbn }}</el-descriptions-item>
        <el-descriptions-item label="出版社">{{ previewBook.publisher }}</el-descriptions-item>
        <el-descriptions-item label="出版日期">{{ previewBook.publish_date }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ getCategoryPath(previewBook.category_id) }}</el-descriptions-item>
        <el-descriptions-item label="馆藏位置">{{ previewBook.location }}</el-descriptions-item>
        <el-descriptions-item label="总数量">{{ previewBook.total_copies }}</el-descriptions-item>
        <el-descriptions-item label="可借数量">{{ previewBook.available_copies }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(previewBook.book_status)">
            {{ getStatusText(previewBook.book_status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="图书简介" :span="2">
          {{ previewBook.description || '暂无简介' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 扫码对话框 -->
    <el-dialog
      v-model="scannerDialog.visible"
      title="扫描ISBN"
      width="400px"
      destroy-on-close
    >
      <steam-barcode-reader
        @decode="handleScanResult"
        style="width: 100%; height: 300px"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Folder, Plus, Edit, Camera } from "@element-plus/icons-vue";
import {
  getAllBookCategory,
  saveBookCategory,
  editBookCategory,
  uploadBookCover,
  addNewBook,
  editBook,
  getBookPagerDataBySearch,
} from "@/api/index";
import { ElMessage, ElMessageBox } from "element-plus";
import SteamBarcodeReader from "@/components/steambarcodereader.vue";

const searchForm = ref({
  bookName: "",
  author: "",
  category: "",
  status: "",
});

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

const tableLoading = ref(false);
const tableData = ref([]);
const sortConfig = ref({
  prop: 'book_id',
  order: 'descending'
});

const getBookList = async () => {
  try {
    tableLoading.value = true;
    
    // 构建查询参数
    const params = {
      currentPage: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      title: searchForm.value.bookName || undefined,
      author: searchForm.value.author || undefined,
      category_id: Array.isArray(searchForm.value.category) 
        ? searchForm.value.category[searchForm.value.category.length - 1]
        : searchForm.value.category,
      book_status: searchForm.value.status,
      sortField: sortConfig.value.prop,
      sortOrder: sortConfig.value.order === 'ascending' ? 'asc' : 'desc'
    };

    // 调用后端API
    const response = await getBookPagerDataBySearch(params);
    if (response.code === 200) {
      tableData.value = response.data.data;
      pagination.value.total = response.data.total;
    } else {
      throw new Error(response.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取图书列表失败:', error);
    ElMessage.error(error.message || '获取图书列表失败');
  } finally {
    tableLoading.value = false;
  }
};

// 搜索处理函数
const handleSearch = () => {
  pagination.value.currentPage = 1;
  getBookList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    bookName: '',
    author: '',
    category: null,
    status: '',
  };
  pagination.value.currentPage = 1;
  getBookList();
};

// 分页处理函数
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  getBookList();
};

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
  getBookList();
};

// 排序处理函数
const handleSortChange = ({ prop, order }) => {
  sortConfig.value = { prop, order };
  getBookList();
};

// 在组件挂载时获取图书列表
onMounted(() => {
  getBookList();
});

// 修改图书状态
const handleChangeStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.book_status === 0 ? '下架' : '上架'}该图书吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    // TODO: 调用后端API修改状态
    ElMessage.success(`${row.book_status === 0 ? '下架' : '上架'}成功`);
    getBookList();
  } catch (error) {
    console.error('修改状态失败:', error);
  }
};

// 原始分类数据
const rawCategories = ref([]);
// 树形分类数据 - 用于el-tree展示
const categories = ref([]);

const categoryDialog = ref({
  visible: false,
  type: "add",
});

const categoryForm = ref({
  id: null,
  name: "",
  parentId: null,
  sort: 0,
});

const defaultProps = {
  children: "children",
  label: "label",
};

const cascaderProps = {
  value: "id",
  label: "label",
  children: "children",
  checkStrictly: true, // 可以选择任意一级
  emitPath: true, // 返回完整路径
};

const categoryFormRef = ref(null);
const categoryRules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
};

//API请求获取图书分类数据
const getBookCategory = async () => {
  try {
    const response = await getAllBookCategory();
    rawCategories.value = response.data;
    // 这里根据实际情况选择非递归或者递归算法实现树形结构
    categories.value = buildCategoryTree(rawCategories.value);
  } catch (error) {
    console.error("获取图书分类失败", error);
  }
};

// 将扁平数据转换为树形结构
// 非递归,数据层级可能很深（如组织架构图）
const transformToTree = (flatData) => {
  // 创建一个映射表，方便通过id快速查找节点
  const map = {};
  const tree = [];

  // 首先将所有节点存入map
  flatData.forEach((item) => {
    map[item.category_id] = {
      ...item, // 展开原对象的所有属性
      id: item.category_id, // 确保有id字段
      label: item.category_name, // Element Plus tree需要label字段显示文本
      children: [], // 初始化children数组
    };
  });

  // 构建树结构
  flatData.forEach((item) => {
    const node = map[item.category_id];
    if (item.parent_id === 0) {
      // 如果是根节点，直接添加到树中
      tree.push(node);
    } else {
      // 否则找到父节点并添加到其children中
      const parent = map[item.parent_id];
      if (parent) {
        parent.children.push(node);
        // 保持子节点排序
        parent.children.sort((a, b) => a.sort_order - b.sort_order);
      }
    }
  });

  // 对根节点进行排序
  tree.sort((a, b) => a.sort_order - b.sort_order);

  return tree;
};

// 使用递归算法实现数据的树形结构
// 该方法未使用，注意是否使用递归算法取决于数据递归的深度，数据层级较浅（如分类通常不超过5-6层），咱们这里最多只有四层
const transformToTreeRecursive = (flatData, parentId = 0) => {
  return flatData
    .filter((item) => item.parent_id === parentId)
    .sort((a, b) => a.sort_order - b.sort_order)
    .map((item) => ({
      ...item,
      id: item.category_id,
      label: item.category_name,
      children: transformToTreeRecursive(flatData, item.category_id),
    }));
};

/** 改进版：易于理解的递归实现
 * 将扁平数组转换为树形结构（递归实现）
 * @param {Array} flatData - 扁平数据数组，每个元素需包含 category_id, parent_id, category_name 等字段
 * @param {number} parentId - 当前层级的父节点ID，默认为0（根节点）
 * @returns {Array} 树形结构数组
 */
const buildCategoryTree = (flatData, parentId = 0) => {
  // 1. 找出当前层级的所有节点
  const currentLevelNodes = flatData.filter(
    (item) => item.parent_id === parentId
  );

  // 2. 按排序字段排序
  const sortedNodes = currentLevelNodes.sort(
    (a, b) => a.sort_order - b.sort_order
  );

  // 3. 为每个节点构建子树
  const tree = sortedNodes.map((node) => {
    // 创建当前节点的基础信息
    const treeNode = {
      ...node, // 保留原始数据
      id: node.category_id, // 确保有id字段
      label: node.category_name, // ElementUI Tree需要的显示字段
      children: [], // 初始化children
    };

    // 递归查找子节点
    treeNode.children = buildCategoryTree(flatData, node.category_id);

    return treeNode;
  });

  return tree;
};

// 组件挂载时获取分类数据
onMounted(() => {
  //初始化图书分类数据
  getBookCategory();
});

// 添加选中分类的响应式引用
const selectedCategory = ref(null);

// 添加分类图书分类处理函数
const handleAddCategory = () => {
  categoryDialog.value.visible = true;
  categoryDialog.value.type = "add";
  // 重置表单前获取选中节点的路径
  const parentPath = selectedCategory.value
    ? findNodePath(categories.value, selectedCategory.value.category_id)
    : null;

  // 重置表单
  categoryForm.value = {
    id: null,
    name: "",
    parentId: parentPath,
    sort: 0,
  };
};

// 添加分类的保存处理函数
const handleSaveCategory = () => {
  categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          category_name: categoryForm.value.name,
          parent_id:
            categoryForm.value.parentId?.[
              categoryForm.value.parentId.length - 1
            ] || 0,
          sort_order: categoryForm.value.sort,
        };

        if (categoryDialog.value.type === "edit") {
          submitData.category_id = categoryForm.value.id;
          await editBookCategory(submitData);
        } else {
          await saveBookCategory(submitData);
        }

        ElMessage.success(
          categoryDialog.value.type === "edit" ? "编辑成功" : "保存成功"
        );
        categoryDialog.value.visible = false;
        // 重置表单
        categoryForm.value = {
          id: null,
          name: "",
          parentId: null,
          sort: 0,
        };
        await getBookCategory();
      } catch (error) {
        console.error(
          categoryDialog.value.type === "edit"
            ? "编辑分类失败:"
            : "保存分类失败:",
          error
        );
        ElMessage.error(
          (categoryDialog.value.type === "edit" ? "编辑" : "保存") +
            "失败：" +
            (error.message || "未知错误")
        );
      }
    }
  });
};

// 处理树节点点击事件，获取选中分类
const handleNodeClick = (data) => {
  selectedCategory.value = data;
};

// 修改编辑处理函数
const handleEditCategory = () => {
  if (!selectedCategory.value) return;

  const parentPath =
    selectedCategory.value.parent_id === 0
      ? null
      : findNodePath(categories.value, selectedCategory.value.parent_id);

  categoryDialog.value.visible = true;
  categoryDialog.value.type = "edit";
  categoryForm.value = {
    id: selectedCategory.value.category_id,
    name: selectedCategory.value.category_name,
    parentId: parentPath,
    sort: selectedCategory.value.sort_order,
  };
};

// 添加用于查找节点路径的工具函数
const findNodePath = (tree, targetId, path = []) => {
  for (const node of tree) {
    if (node.id === targetId) {
      return [...path, node.id];
    }
    if (node.children && node.children.length) {
      const foundPath = findNodePath(node.children, targetId, [
        ...path,
        node.id,
      ]);
      if (foundPath) return foundPath;
    }
  }
  return null;
};

// 新增图书相关的响应式数据
const bookDialog = ref({
  visible: false,
  type: "add",
});

const bookForm = ref({
  book_id: null,
  book_cover: "", // 修改为book_cover
  isbn: "",
  title: "",
  author: "",
  category_id: null,
  publisher: "",
  publish_date: "", // 新增出版日期
  total_copies: 1,  // 新增总数量
  available_copies: 1, // 新增可借阅数量
  borrow_copies: 0, // 新增已借阅数量
  location: "",
  description: "", // 新增图书简介字段
  book_status: 0  // 默认为在库状态
});

const bookFormRef = ref(null);

const bookRules = {
  title: [
    { required: true, message: "请输入书名", trigger: "blur" },
    { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" },
  ],
  author: [{ required: true, message: "请输入作者", trigger: "blur" }],
  isbn: [{ required: true, message: "请输入ISBN", trigger: "blur" }],
  publisher: [{ required: true, message: "请输入出版社", trigger: "blur" }],
  publish_date: [{ required: true, message: "请选择出版日期", trigger: "change" }],
  total_copies: [
    { required: true, message: "请输入图书总数量", trigger: "blur" },
    { type: 'number', min: 1, message: "数量必须大于0", trigger: "blur" }
  ],
  borrow_copies:[{ required: true, message: "请输入图书已借阅数量", trigger: "blur" },
  { type: 'number', min: 0, message: "数量必须大于等于0", trigger: "blur" }],
  location: [{ required: true, message: "请输入馆藏位置", trigger: "blur" }],
  category_id: [{ required: true, message: "请选择图书分类", trigger: "change" }],
  description: [
    { max: 500, message: "简介长度不能超过500字", trigger: "blur" }
  ],
  book_status: [{ required: true, message: "请选择图书状态", trigger: "change" }],
};

// 添加图书相关的方法
const handleAddBook = () => {
  bookDialog.value.visible = true;
  bookDialog.value.type = "add";
  bookForm.value = {
    book_id: null,
    title: "",
    author: "",
    isbn: "",
    publisher: "",
    publish_date: "",
    location: "",
    status: "in_stock",
    book_cover: "",
    category_id: null,
    total_copies: 1,
    borrow_copies:0, //已借阅数量
    description: "", // 新增图书简介字段
    book_status: 0  // 默认为在库状态
  };
};

const beforeCoverUpload = (file) => {
  // 检查文件类型
  const fileExt = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
  const isValidType = ['.jpg', '.jpeg', '.png'].includes(fileExt);
  
  // 检查文件大小（2MB）
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isValidType) {
    ElMessage.error('只支持JPG、JPEG和PNG格式的图片！');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过2MB！');
    return false;
  }
  return true;
};

const handleCoverSuccess = async (params) => {
  try {
    const formData = new FormData();
    formData.append('file', params.file);
    
    const response = await uploadBookCover(formData);
    if (response.code === 200) {
      bookForm.value.cover = response.data; // response.data 是完整的图片URL
      ElMessage.success(response.message || '封面上传成功');
    } else {
      throw new Error(response.message || '上传失败');
    }
  } catch (error) {
    console.error('封面上传失败:', error);
    ElMessage.error(error.message || '封面上传失败，请重试');
  }
};

// 添加扫码对话框控制
const scannerDialog = ref({
  visible: false,
});

// 处理扫码结果
const handleScanResult = (result) => {
  bookForm.value.isbn = result;
  scannerDialog.value.visible = false;
  // 模拟根据ISBN获取图书信息
  // 实际项目中应该调用获取图书信息的API
  ElMessage.success(`扫描成功：${result}`);
};

// 打开扫码器
const openScanner = () => {
  scannerDialog.value.visible = true;
};

// 添加图书总数变化处理函数
const handleTotalCopiesChange = (val) => {
  // 当总数量改变时，自动调整可借数量
  if (bookForm.value.total_copies < bookForm.value.borrow_copies) {
    bookForm.value.borrow_copies = bookForm.value.total_copies;
  }
  // 当可借数量改变时，自动调整总数量
  if (bookForm.value.total_copies < bookForm.value.borrow_copies) {
    bookForm.value.total_copies = bookForm.value.borrow_copies;
  }
};

// 修改保存图书的方法
const handleSaveBook = async () => {
  await bookFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备提交的数据
        const submitData = {
          ...bookForm.value,
          category_id: Array.isArray(bookForm.value.category_id) 
            ? bookForm.value.category_id[bookForm.value.category_id.length - 1] 
            : bookForm.value.category_id,
          book_cover: bookForm.value.cover
        };

        // 处理编辑和新增的不同场景
        if (bookDialog.value.type === 'edit') {
          // 编辑时需要传入book_id
          submitData.book_id = bookForm.value.book_id;
          const response = await editBook(submitData);
          
          if (response.code === 200) {
            ElMessage.success('图书编辑成功');
            bookDialog.value.visible = false;
            getBookList(); // 刷新列表
          } else {
            throw new Error(response.message || '编辑失败');
          }
        } else {
          // 新增图书的逻辑保持不变
          const response = await addNewBook(submitData);
          if (response.code === 200) {
            ElMessage.success('图书添加成功');
            bookDialog.value.visible = false;
            getBookList();
          } else {
            throw new Error(response.message || '添加失败');
          }
        }
      } catch (error) {
        console.error('保存图书失败:', error);
        ElMessage.error(error.message || '保存失败，请重试');
      }
    }
  });
};

// 添加状态转换的工具函数
const getStatusText = (status) => {
  const statusMap = {
    0: '在库',
    1: '借出',
    2: '维护中'
  };
  return statusMap[status] || '未知状态';
};

const getStatusType = (status) => {
  const typeMap = {
    0: 'success',
    1: 'warning',
    2: 'info'
  };
  return typeMap[status] || 'info';
};

// 添加预览对话框的控制变量
const previewDialog = ref({
  visible: false
});

// 添加预览图书数据
const previewBook = ref({});

// 编辑图书
const handleEditBook = (row) => {
  bookDialog.value.visible = true;
  bookDialog.value.type = 'edit';
  
  // 根据所选分类构建完整的分类路径
  const categoryPath = findNodePath(categories.value, row.category_id);
  
  // 填充表单数据
  bookForm.value = {
    book_id: row.book_id,
    title: row.title,
    author: row.author,
    isbn: row.isbn,
    publisher: row.publisher,
    publish_date: row.publish_date,
    location: row.location,
    total_copies: row.total_copies,
    available_copies: row.available_copies,
    borrow_copies: row.borrow_copies,
    book_status: row.book_status,
    cover: row.book_cover,
    description: row.description || '', // 添加简介字段
    category_id: categoryPath
  };
};

// 查看图书详情
const handleViewBook = (row) => {
  previewBook.value = row;
  previewDialog.value.visible = true;
};

// 获取分类完整路径名称
const getCategoryPath = (categoryId) => {
  const path = findNodePath(categories.value, categoryId);
  if (!path) return '未知分类';
  
  // 根据路径ID数组获取分类名称
  const categoryNames = path.map(id => {
    const findCategory = (tree, targetId) => {
      for (const node of tree) {
        if (node.id === targetId) return node.label;
        if (node.children && node.children.length) {
          const found = findCategory(node.children, targetId);
          if (found) return found;
        }
      }
      return null;
    };
    return findCategory(categories.value, id);
  });
  
  return categoryNames.join(' / ');
};
</script>

<style scoped>
.books-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.category-card {
  height: calc(100vh - 140px);
}

.book-list {
  min-height: calc(100vh - 140px);
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.category-actions {
  display: flex;
  gap: 8px;
}

.category-header .title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.category-header .title .el-icon {
  font-size: 18px;
  color: var(--el-color-primary);
}

.category-card :deep(.el-card__header) {
  padding: 0 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background-color: var(--el-fill-color-blank);
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}

.book-cover-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.book-cover-uploader:hover {
  border-color: var(--el-color-primary);
}

.book-cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 160px;
  text-align: center;
  line-height: 160px;
}

.book-cover {
  width: 120px;
  height: 160px;
  display: block;
  object-fit: cover;
}

/* 添加扫码对话框样式 */
:deep(.el-dialog__body) {
  padding: 0;
  overflow: hidden;
}

.cover-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cover-preview {
  width: 140px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
  overflow: hidden;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: var(--el-text-color-secondary);
}

.upload-placeholder .el-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.book-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  text-align: center;
}

.book-cover-uploader {
  width: 140px;
}

.book-cover-uploader:hover {
  border-color: var(--el-color-primary);
}

.cover-section {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.section-title {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 16px;
  align-self: flex-start;
}

.cover-preview {
  width: 180px;  /* 增加预览尺寸 */
  height: 260px; /* 增加预览尺寸 */
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
  overflow: hidden;
}

.book-cover-uploader {
  width: 180px; /* 匹配预览尺寸 */
}

.book-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

/* 添加详情预览样式 */
:deep(.el-descriptions__label) {
  width: 120px;
}

:deep(.el-descriptions__content) {
  min-height: 40px;
}
</style>
